package com.wang.cloud.common.encrypt.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;

/**
 * @author wang ye
 * @date 2024/7/5
 */
public class SM4Util {

    /**
     * 生成SM4密钥
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     */
    public static String generatorSM4Key() throws NoSuchAlgorithmException, NoSuchProviderException {
        // 添加Bouncy Castle提供者
        Security.addProvider(new BouncyCastleProvider());

        // 初始化KeyGenerator，指定算法为SM4
        KeyGenerator keyGenerator = KeyGenerator.getInstance("SM4", "BC");

        // 生成密钥
        SecretKey secretKey = keyGenerator.generateKey();

        // 打印密钥
        String sm4Key = bytesToHex(secretKey.getEncoded());
        return sm4Key;
    }

    // 辅助方法，将字节数组转换为十六进制字符串
    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
